/*
 Microsoft Public License (Ms-PL)

This license governs use of the accompanying software. If you use the software, you accept this license. If you do not accept the license, do not use the software.

1. Definitions

The terms "reproduce," "reproduction," "derivative works," and "distribution" have the same meaning here as under U.S. copyright law.

A "contribution" is the original software, or any additions or changes to the software.

A "contributor" is any person that distributes its contribution under this license.

"Licensed patents" are a contributor's patent claims that read directly on its contribution.

2. Grant of Rights

(A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create.

(B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software.

3. Conditions and Limitations

(A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks.

(B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically.

(C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software.

(D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license.

(E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement.
 */
/*
 *Copyright - Microsoft cooperation  2007
 */
package com.aluna.openxml.excel.type;

import java.io.ByteArrayOutputStream;
import java.math.BigDecimal;
import java.text.DateFormat;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;

import com.aluna.openxml.excel.ExcelFile;
import com.aluna.openxml.excel.Range;
import com.aluna.openxml.excel.Row;
import com.aluna.openxml.jaxb.chart.*;

/**
 * This class represents a chart in the XLSX file 
 * @author Liran Zelkha
 *
 */
public class ChartType extends ExcelFileType {
	private Range valueRange;
	private Range categoryRange;
	
	public ChartType(Range categoryRange, Range valueRange) {
		this.categoryRange = categoryRange;
		this.valueRange = valueRange;
	}
	
	public byte[] store() throws Exception {
		ChartSpace chartSpace = new ChartSpace();
		Chart chart = new Chart();
		chartSpace.setChart(chart);
		
		Lang lang = new Lang();
		
		// TODO: Dynamic		
		lang.setVal("he-IL");
		
		Layout layout = new Layout();
		Title title = new Title();
		
		title.setLayout(layout);
		chart.setTitle(title);

		PlotArea plotArea = new PlotArea();
		chart.setPlotArea(plotArea);
		
		Layout plotLayout = new Layout();
		plotArea.setLayout(plotLayout);
		
		
		LineChart lineChart = new LineChart();
		plotArea.setLineChart(lineChart);
		
		Grouping grouping = new Grouping();
		grouping.setVal("standard");
		lineChart.setGrouping(grouping);
		
		Ser ser = new Ser();
		
		lineChart.setSer(ser);
		
		Idx idx = new Idx();
		idx.setVal(0);
		
		ser.setIdx(idx);
		
		Order order = new Order();
		order.setVal(0);
		
		ser.setOrder(order);

		Tx tx = new Tx();
		
		StrRef strRef = new StrRef();
		
		tx.setStrRef(strRef);

		// This is the title of the graph
		ser.setTx(tx);
		
		// TODO: Dynamic		
		strRef.setF("'Stocks Values'!$C$1");
		
		StrCache strCache = new StrCache();
		
		strRef.setStrCache(strCache);
		
		PtCount ptCount= new PtCount();
		ptCount.setVal(1);
		
		strCache.setPtCount(ptCount);
		
		Pt pt = new Pt();
		
		strCache.setPt(pt);
		
		// TODO: Dynamic
		pt.setIdx(0);
		pt.setV("Value");
		
		Marker marker = new Marker();
		Symbol symbol = new Symbol();
		symbol.setVal("none");
		
		marker.setSymbol(symbol);
		
		ser.setMarker(marker);

		Cat cat = new Cat();
		ser.setCat(cat);
		
		MultiLvlStrRef multiRef = new MultiLvlStrRef();
		
		cat.setMultiLvlStrRef(multiRef);
		// The category axis
		
		multiRef.setF(categoryRange.getRangeName());
		
		MultiLvlStrCache cache = new MultiLvlStrCache();
		multiRef.setMultiLvlStrCache(cache);
		
		PtCount count = new PtCount();
		count.setVal(categoryRange.getRowIterator().size() - 2);
		cache.setPtCount(count);

		Lvl level = new Lvl();
		Lvl level2 = new Lvl();
		
		cache.getLvl().add(level);
		cache.getLvl().add(level2);
		
		DateFormat format = DateFormat.getDateInstance(DateFormat.SHORT);

		for (short i = 0; i < categoryRange.getRowIterator().size() - 2; ++i) {
			Row r = categoryRange.getRowIterator().get(i + 2);
			
			
			Pt point = new Pt();
			point.setIdx(i);
			point.setV(format.format(r.getCell(1).getDataAsDate()));
			
			level.getPt().add(point);
			
			Pt point2 = new Pt();
			point2.setIdx(i);
			
			point2.setV(r.getCell(0).getData().toString());
			level2.getPt().add(point2);
			
		}
		
		
		Val val = new Val();
		
		ser.setVal(val);
		
		
		NumRef numRef = new NumRef();
		numRef.setF(valueRange.getRangeName());
		
		val.setNumRef(numRef);
		
		NumCache numCache = new NumCache();
		numCache.setFormatCode("General");

		numRef.setNumCache(numCache);
		
		PtCount ptCount2 = new PtCount();
		ptCount2.setVal(valueRange.getRowIterator().size() - 2);
		
		numCache.setPtCount(ptCount2);

		for (short i = 0; i < valueRange.getRowIterator().size() - 2; ++i) {
			Row r = valueRange.getRowIterator().get(i + 2);
			
			Pt point = new Pt();
			
			point.setIdx(i);
			point.setV(r.getCell(2).getData().toString());
			
			numCache.getPt().add(point);
		}
		
		Marker marker2 = new Marker();
		marker2.setVal(1);
		lineChart.setMarker(marker2);

		AxId axisId =  new AxId();
		axisId.setVal(87477632);
		lineChart.getAxId().add(axisId);

		AxId axisId2 =  new AxId();
		axisId2.setVal(88126592);
		lineChart.getAxId().add(axisId2);
		
		CatAx categoryAxis = new CatAx();
		plotArea.setCatAx(categoryAxis);
		
		AxId axId = new AxId();
		axId.setVal(87477632);
		categoryAxis.setAxId(axId);
		
		Scaling scaling = new Scaling();
		Orientation orientation = new Orientation();
		orientation.setVal("maxMin");
		scaling.setOrientation(orientation);
		categoryAxis.setScaling(scaling);

		AxPos axPos = new AxPos();
		axPos.setVal("b");
		categoryAxis.setAxPos(axPos);
		

		categoryAxis.setTickLblPos(new TickLblPos("nextTo"));
		categoryAxis.setCrossAx(new CrossAx(88126592));
		categoryAxis.setCrosses(new Crosses("autoZero"));

		Auto auto = new Auto();
		auto.setVal(1);
		categoryAxis.setAuto(auto);
		
		LblAlgn lblAlign = new LblAlgn();
		lblAlign.setVal("ctr");
		categoryAxis.setLblAlgn(lblAlign);
		
		LblOffset offset = new LblOffset();
		offset.setVal(100);
		categoryAxis.setLblOffset(offset);
		
		ValAx valueAxis = new ValAx();
		plotArea.setValAx(valueAxis);
		
		AxId valueAxisId = new AxId();
		valueAxisId.setVal(88126592);
		valueAxis.setAxId(valueAxisId);

		Orientation valueOrientation = new Orientation();
		valueOrientation.setVal("minMax");
		Scaling valueScaling = new Scaling();
		valueScaling.setOrientation(valueOrientation);
		valueAxis.setScaling(valueScaling);
		
		AxPos valueAxisPos = new AxPos();
		valueAxisPos.setVal("r");
		valueAxis.setAxPos(valueAxisPos);
		valueAxis.setMajorGridlines(new MajorGridlines());

		NumFmt numberFormat = new NumFmt();
		valueAxis.setNumFmt(numberFormat);
		
		numberFormat.setFormatCode("General");
		numberFormat.setSourceLinked(1);
		
		valueAxis.setTickLblPos(new TickLblPos("nextTo"));
		valueAxis.setCrossAx(new CrossAx(87477632));
		valueAxis.setCrosses(new Crosses("autoZero"));
		valueAxis.setCrossBetween(new CrossBetween("between"));
		
		
		Legend legend = new Legend();
		chart.setLegend(legend);
		legend.setLegendPos(new LegendPos("l"));
		legend.setLayout(new Layout());
		
		chart.setPlotVisOnly(new PlotVisOnly(1));

		PrintSettings printSettings = new PrintSettings();
		chartSpace.setPrintSettings(printSettings);
		
		
		printSettings.setHeaderFooter(new HeaderFooter());
		
		PageMargins margins = new PageMargins();
		printSettings.setPageMargins(margins);
 
		margins.setB(new BigDecimal(0.75));
		margins.setL(new BigDecimal(0.75));
		margins.setR(new BigDecimal(0.75));
		margins.setT(new BigDecimal(0.75));
		
		margins.setHeader(new BigDecimal(0.75));
		margins.setFooter(new BigDecimal(0.75));
		
		printSettings.setPageSetup(new PageSetup());
		
//		XmlOptions opts = new XmlOptions();
//		
//		Map suggestedPrefixes = new HashMap();
//		suggestedPrefixes.put("http://schemas.openxmlformats.org/drawingml/2006/main", "a");
//		suggestedPrefixes.put("http://schemas.openxmlformats.org/drawingml/2006/chart", "c");
//		suggestedPrefixes.put("http://schemas.openxmlformats.org/officeDocument/2006/relationships", "r");
//		
//		opts.setSaveSuggestedPrefixes(suggestedPrefixes);

//		chartSpaceDoc.documentProperties().setStandalone(true);
//		opts.setSaveNamespacesFirst();
//		opts.setSaveAggressiveNamespaces();

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		JAXBContext context = JAXBContext.newInstance("com.aluna.openxml.jaxb.chart");
		Marshaller marshaller = context.createMarshaller();
		marshaller.marshal(chartSpace, baos);
		return baos.toByteArray();
	}

	public String getContentType() throws Exception {
		return "application/vnd.openxmlformats-officedocument.drawingml.chart+xml";
	}

	public void load() {
		throw new UnsupportedOperationException();
	}
	
	public byte[] update(ExcelFile file) throws Exception {
		throw new UnsupportedOperationException();
	}

	public String getFileName() {
		throw new UnsupportedOperationException();
	}
}
